// 变量定义
var canvasHistory = [];// 图像历史数据
var strHistory = [];// 坐标历史数据
var step = -1;// 笔画次数
var canvasWidth = window.innerWidth;// 可视区域宽
var canvasHeight = window.innerHeight;// 可视区域高
var positionTimePenSize = "";// 
var isDrawing = false;// 是否在画
var ws = new WebSocket("ws://" + window.location.host + ":8004/echo");// WS服务器
var canvas = document.getElementById('draw');// 获取canvas元素
var ctx = canvas.getContext('2d');// 准备绘制
var pos = { x: 0, y: 0 };
var co = document.getElementById('draw').offsetTop;
var xx = 0, yy = 0;
var pensize = 20;

window.addEventListener('resize', resize);
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mouseenter', setPosition);
document.addEventListener('mousedown', startDraw);
document.addEventListener('mouseup', stopDraw);

document.addEventListener('touchmove', draw_, { passive: false });// passive 默认开，preventDefault无效
document.addEventListener('touchstart', setPosition_, false);
document.addEventListener('touchend', setPosition_c, false);
document.addEventListener('touchstart', startDraw_, false);
document.addEventListener('touchend', stopDraw_, false);

resize();
// 设置画布大小
function resize() {
  ctx.width = window.innerWidth;
  ctx.height = window.innerHeight;
}

// 加载当前坐标等数据到textarea以供拷贝
function getData() {
  document.getElementById("s").innerHTML = "";
  document.getElementById("s").innerHTML = positionTimePenSize;
  step < 0 ? document.getElementById("undo").disabled = true : document.getElementById("undo").disabled = false;
}

// websocket服务器连接成功后触发
ws.onopen = function (evt) {
  console.log("Connection open ...");
};

// websocket服务器收到消息触发
ws.onmessage = function (evt) {
};

// websocket服务器连接关闭触发
ws.onclose = function (evt) {
  console.log("Connection closed.");
};

// 获得鼠标指针坐标
function setPosition(e) {
  pos.x = (e.clientX < 0 ? 0 : e.clientX);
  pos.y = (e.clientY - co < 0 ? 0 : e.clientY - co);
  xx = e.clientX;
  yy = e.clientY - co;
}

// 获得触摸坐标
function setPosition_(e) {
  pos.x = (e.touches[0].clientX < 0 ? 0 : e.touches[0].clientX);
  pos.y = (e.touches[0].clientY - co < 0 ? 0 : e.touches[0].clientY - co);
  xx = e.touches[0].clientX;
  yy = e.touches[0].clientY - co;
}

// 获得触摸结束坐标
function setPosition_c(e) {
  pos.x = (e.changedTouches[0].clientX < 0 ? 0 : e.changedTouches[0].clientX);
  pos.y = (e.changedTouches[0].clientY - co < 0 ? 0 : e.changedTouches[0].clientY - co);
  xx = e.changedTouches[0].clientX;
  yy = e.changedTouches[0].clientY - co;
}

// 改变笔粗细
function changepensize() {
  pensize = document.getElementById("size").value * 0.5 + 1;
  console.log(document.getElementById("size").value)
}

// 绘画-鼠标
function draw(e) {
  if ((xx < 0 || 0 > yy) && isDrawing == false) return;
  if (e.buttons !== 1) return; // if mouse is pressed.....

  //start失效
  if (isDrawing == false) {
    startDraw();
  }
  var color = document.getElementById('hex').value;

  ctx.beginPath(); // begin the drawing path

  ctx.lineWidth = pensize; // width of line 
  ctx.lineCap = 'round'; // rounded end cap
  ctx.strokeStyle = color; // hex color of line

  ctx.moveTo(pos.x, pos.y); // from position
  setPosition(e);
  ctx.lineTo(pos.x, pos.y); // to position

  ctx.stroke(); // draw it!
  positionTimePenSize += pos.x + " " + pos.y + " " + Date.now() + " " + pensize + "\n";
}

// 绘画-触摸
function draw_(e) {
  e.preventDefault();
  if ((0 > xx || 0 > yy) && isDrawing == false) return;

  //start失效
  if (isDrawing == false) {
    
    startDraw();
  }
  var color = document.getElementById('hex').value;

  ctx.beginPath(); // begin the drawing path

  ctx.lineWidth = pensize; // width of line 
  ctx.lineCap = 'round'; // rounded end cap
  ctx.strokeStyle = color; // hex color of line

  ctx.moveTo(pos.x, pos.y); // from position
  setPosition_(e);
  ctx.lineTo(pos.x, pos.y); // to position

  ctx.stroke(); // draw it!
  positionTimePenSize += pos.x + " " + pos.y + " " + Date.now() + " " + pensize + "\n";
}

// 开始绘画时触发-鼠标
function startDraw() {
  if (0 > yy || 0 > xx) return;
  document.getElementById("c").innerHTML = "drawing";
  if (isDrawing == true) {
    //end失效
    stopDraw();
  }
  isDrawing = true;
  step++;
  if (step < canvasHistory.length) {
    canvasHistory.length = step; // 截断数组
    strHistory.length = step;
  }
  positionTimePenSize += "0 0 0 0\n";
}

// 开始绘画时触发-触摸
function startDraw_() {
  if (0 > yy || 0 > xx) return;
  document.getElementById("c").innerHTML = "drawing";
  if (isDrawing == true) {
    //end失效
    stopDraw();
  }
  isDrawing = true;
  step++;
  if (step < canvasHistory.length) {
    canvasHistory.length = step; // 截断数组
    strHistory.length = step;
  }
  positionTimePenSize += "0 0 0 0\n";
}

// 停止绘画时触发-鼠标
function stopDraw() {
  if (isDrawing == false && (0 > yy || 0 > xx)) return;
  document.getElementById("c").innerHTML = "complete";
  document.getElementById("s").innerHTML = "";
  isDrawing = false;
  document.getElementById("undo").disabled = false;
  canvasHistory.push(canvas.toDataURL()); // 添加新的绘制到历史记录
  strHistory.push(positionTimePenSize);
  step < 0 ? document.getElementById("undo").disabled = true : document.getElementById("undo").disabled = false;
  step < canvasHistory.length - 1 ? document.getElementById("redo").disabled = false : document.getElementById("redo").disabled = true;
}

// 停止绘画时触发-触摸
function stopDraw_() {
  if (isDrawing == false && (0 > yy || 0 > xx)) return;
  document.getElementById("c").innerHTML = "complete";
  document.getElementById("s").innerHTML = "";
  isDrawing = false;
  document.getElementById("undo").disabled = false;
  canvasHistory.push(canvas.toDataURL()); // 添加新的绘制到历史记录
  strHistory.push(positionTimePenSize);
  step < 0 ? document.getElementById("undo").disabled = true : document.getElementById("undo").disabled = false;
  step < canvasHistory.length - 1 ? document.getElementById("redo").disabled = false : document.getElementById("redo").disabled = true;
}

// 撤销
function canvasUndo() {
  document.getElementById("redo").disabled = false;
  if (step >= 0) {
    step--;
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    if (step >= 0) {

      let canvasPic = new Image();
      canvasPic.src = canvasHistory[step];
      positionTimePenSize = strHistory[step];
      canvasPic.addEventListener('load', () => {
        ctx.drawImage(canvasPic, 0, 0);
      });
    } else {
      positionTimePenSize = "";
    }

  } else {
    console.log('不能再继续撤销了');
  }
  step < 0 ? document.getElementById("undo").disabled = true : document.getElementById("undo").disabled = false;
}

// 反撤销
function canvasRedo() {
  console.log(canvasHistory.length)
  document.getElementById("undo").disabled = false;
  if (step < canvasHistory.length - 1) {
    step++;
    let canvasPic = new Image();
    canvasPic.src = canvasHistory[step];
    positionTimePenSize = strHistory[step];
    canvasPic.addEventListener('load', () => {
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.drawImage(canvasPic, 0, 0);
    });
  } else {
    console.log('已经是最新的记录了');
  }
  step < canvasHistory.length - 1 ? document.getElementById("redo").disabled = false : document.getElementById("redo").disabled = true;
}

// 发送坐标时间笔大小数据到服务器data.txt
function sendData() {
  if (ws.readyState == 1) {
    ws.send(positionTimePenSize);
    $.message('已发送');
  } else {
    $.message({ message: '未连接服务器,开启服务器刷新重试', type: "error" });
  }
}

